﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Common.Extension
{
    /// <summary>
    /// 集合扩展（IEnumerable）
    /// </summary>
    public static class EnumerableExtension
    {
        #region IEnumerable转为IEnumerable<object>
        /// <summary>
        /// IEnumerable转为IEnumerable<object>
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static IEnumerable<object> ToEnumrableT(this IEnumerable list)
        {
            var en = list.GetEnumerator();
            while (en.MoveNext())
            {
                yield return en.Current;
            }
            en = null;
        }
        #endregion

        #region 通过索引获取集合数据
        /// <summary>
        /// 通过索引获取集合数据
        /// </summary>
        /// <param name="list"></param>
        /// <param name="idx"></param>
        /// <returns></returns>
        public static object GetByIndex(this IEnumerable list, int idx)
        {
            var en = list.GetEnumerator();
            int i = 0;
            object r = null;
            while (en.MoveNext())
            {
                if (i == idx)
                {
                    r = en.Current;
                    break;
                }
                i++;
            }
            en = null;
            return r;
        }
        #endregion

        #region 集合不为null并且有至少一个元素
        /// <summary>
        /// 集合不为null并且有至少一个元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static bool HasElement<T>(this IEnumerable<T> list)
        {
            return list != null && list.Any();
        }
        #endregion

        #region 遍历集合，执行act
        /// <summary>
        /// 遍历集合，执行act
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="act">每一项上执行的方法</param>
        public static void Each<T>(this IEnumerable<T> list, Action<T> act)
        {
            using (var en = list.GetEnumerator())
            {
                while (en.MoveNext())
                    act(en.Current);
            }
        }
        #endregion

        #region 合并集合数据
        /// <summary>
        /// 合并集合数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr"></param>
        /// <param name="separator"></param>
        /// <param name="emptyModel"></param>
        /// <returns></returns>
        public static string JoinStr<T>(this IEnumerable<T> arr, string separator = ",", int emptyModel = 1)
        {
            return emptyModel == 1 ? (string.Join(separator, arr.Select(c => c + ""))) : (string.Join(separator, arr.Select(c => c + "").Where(c => c.Length > 0)));
        }
        #endregion
    }
}